package com.lyq.gift.exception.handler;

import com.lyq.gift.exception.code.ErrorCode;
import com.lyq.gift.exception.exception.BusinessException;
import com.lyq.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice //执行所有controller方法都会执行try,里面通过Exceptionhandler告诉它要捕获哪些异常
public class GlobalExceptionHandler {

    //捕获BusinessException
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();  //可以预见的异常
        //有多种错误码
        return AjaxResult.me().setSuccess(false)
                .setErrorCode(e.getErrorCode()).setMessage(e.getMessage());
    }

    //捕获Exception
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace(); //系统异常
        BindingResult bindingResult = e.getBindingResult();

        //获取所有的字段验证错误
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        //拼接所有字段错误为xx,yy,zz
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < fieldErrors.size() ; i++) {
            FieldError error = fieldErrors.get(0);
            String msg = error.getDefaultMessage();
            if (i==fieldErrors.size()-1) //最后一个不要逗号
                 sb.append(msg);
            else {
                sb.append(msg).append(",");
            }

        }
        return AjaxResult.me().setSuccess(false)
                .setErrorCode(ErrorCode.ERROR_CODE_400.getCode()).setMessage(sb.toString());
    }
    //捕获Exception
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace(); //系统异常
        return AjaxResult.me().setSuccess(false)
                .setErrorCode(ErrorCode.ERROR_CODE_500.getCode()).setMessage(ErrorCode.ERROR_CODE_500.getMessage());
    }
}
